package com.dgut.courses_selecting_sys.rabbitmq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dgut.courses_selecting_sys.constants.CourseStatus;
import com.dgut.courses_selecting_sys.constants.RabbitMqKey;
import com.dgut.courses_selecting_sys.constants.RedisKey;
import com.dgut.courses_selecting_sys.entity.Course;
import com.dgut.courses_selecting_sys.mapper.CourseMapper;
import com.dgut.courses_selecting_sys.utils.RedisUtil;
import com.dgut.courses_selecting_sys.utils.ShiroUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
@RabbitListener(queuesToDeclare = @Queue(value = RabbitMqKey.COURSE_TO_ING_DELAY_PROCESS_QUEUE, durable = "true"))
public class CourseToIngConsumer {
    @Autowired
    CourseMapper courseMapper;
    @Autowired
    RedisUtil redisUtil;

    @RabbitHandler
    public void changeToIngStatus(String message) {
        Integer id = Integer.valueOf(message);
        Course courseById = courseMapper.selectById(id);
        if (courseById != null && courseById.getStatus().equals(String.valueOf(CourseStatus.CHOICE))) {
//            Integer deptId = courseById.getDeptId();
//            Object arrayStr =redisUtil.get(RedisKey.COURSE_FOR_CHOOSE_BY_DEPT_ID + deptId);
//            List<Course> courseList = new ArrayList<>();
//            if (arrayStr!=null){
//                courseList = JSONObject.parseArray(arrayStr.toString(), Course.class);
//            }
//            List<Course> newCourseList = courseList.stream().filter(e -> !e.getCourseId().equals(courseById.getCourseId())).collect(Collectors.toList());
//            redisUtil.set(RedisKey.COURSE_FOR_CHOOSE_BY_DEPT_ID+deptId, JSON.toJSON(newCourseList));
            Course courseDb = new Course();
            courseDb.setStatus(String.valueOf(CourseStatus.ING));
            courseDb.setCourseId(courseById.getCourseId());
            courseMapper.updateById(courseDb);
            log.info("课程开选结束通知:"+courseDb);
        }
    }
}
